/* eslint-disable @typescript-eslint/no-unused-vars */
import { Modal, message, PaginationProps } from 'antd';
import { useState, useCallback, useMemo } from 'react';
import { exceptSpace } from '@/utils';
import { useRefState } from './index';

export interface IPagination {
  current?: number;
  pageSize?: number;
  total?: number;
}
export interface IParams {
  current: number;
  pageSize: number;
  [key: string]: any;
}
interface IProps {
  params?: Record<string, any>;
  api: {
    getList: (params: IParams) => Promise<any>;
    downloadExcel?: (params: { ids: string }) => Promise<any>;
    deleteItem?: (params: { id: string }) => Promise<any>;
    batchDelete?: (params: { ids: string }) => Promise<any>;
  };
}

export default function useMakeList<Item = {}>({ params = {}, api }: IProps) {
  const [selectedRowKeys, setSelectedRowKeys] = useState<Array<string>>([]);

  // --- 列表请求参数 ---
  const [paginationRef, setPagination] = useRefState<IPagination>({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  // --- 额外的参数，通常是表单元素的值 ---
  const [extraParamsRef, setExtraParams] = useRefState<Record<string, any>>({});

  // --- 列表 ---
  const [list, setList] = useState<Item[]>([]);

  // --- loading状态 ---
  const [loading, setLoading] = useState(false);
  const [downloadPending, setDownloadPending] = useState(false);

  // --- 处理请求参数 ---
  const getQueryParams = useCallback(
    (): IParams =>
      exceptSpace({
        ...extraParamsRef.current,
        current: paginationRef.current.current || 1,
        pageSize: paginationRef.current.pageSize || 10,
        ...params,
      }),
    [JSON.stringify(params)],
  );

  //  --- 删除后处理页码 ---
  const calcPageAfterDelete = useCallback(
    (delCount: number): void => {
      setPagination(
        (prev: IPagination): IPagination => {
          const newTotal = (prev.total || 0) - delCount;
          let newTotalPages = Math.ceil(newTotal / prev.pageSize!);
          newTotalPages = newTotalPages <= 0 ? 1 : newTotalPages;
          return {
            ...prev,
            total: newTotal,
            current: prev.current! > newTotalPages ? newTotalPages : prev.current,
          };
        },
      );
    },
    [setPagination],
  );

  // --- 获取表格数据 ---
  const getList = useCallback(() => {
    setLoading(true);
    api
      .getList(getQueryParams())
      .then((res: any) => {
        if (res.success) {
          setPagination(prev => ({ ...prev, total: res?.data?.total || 0 }));
          const { pageSize = 10, current = 1 } = paginationRef.current;
          let records = [];
          // console.log('res', res)
          if (res?.data instanceof Array) {
            records = res.data;
          }
          if (res?.data?.records instanceof Array) {
            records = res.data.records;
          }
          setList(
            records.map((item: Item, index: number) => ({
              ...item,
              __index: (current - 1) * pageSize + index + 1,
            })),
          );
        }
      })
      .finally(() => {
        setLoading(false);
      });
  }, [getQueryParams, setPagination]);

  // --- 批量下载 ---
  const downloadExcel = useCallback(() => {
    const selections = selectedRowKeys.join(','); // 看接口入参如何命名

    setDownloadPending(true);
    api.downloadExcel?.({ ids: selections }).finally(() => {
      setDownloadPending(false);
    });
  }, [getQueryParams, selectedRowKeys]);

  // --- 删除record ---
  const deleteItem = useCallback(
    (id: string) => {
      api.deleteItem?.({ id }).then(res => {
        if (res.success) {
          calcPageAfterDelete(1);
          getList();
          message.success('删除成功');
        } else {
          message.error(res.errorMsg || '删除失败');
        }
      });
    },
    [getList, calcPageAfterDelete],
  );

  // --- 批量删除 ---
  const batchDelete = useCallback(() => {
    Modal.confirm({
      title: '确认删除',
      content: '是否删除选中数据？',
      okText: '确认',
      cancelText: '取消',
      onOk() {
        return api
          .batchDelete?.({
            ids: selectedRowKeys.join(','),
          })
          .then(res => {
            if (res.success) {
              calcPageAfterDelete(selectedRowKeys.length);
              getList();
              setSelectedRowKeys([]);
            }
          });
      },
    });
  }, [selectedRowKeys, getList]);

  // --- 行选择配置 ---
  const rowSelection = useMemo(
    () => ({
      onChange: (keys: string[]) => {
        setSelectedRowKeys(keys);
      },
      selectedRowKeys,
      preserveSelectedRowKeys: true,
    }),
    [selectedRowKeys],
  );

  // --- 分页器设置 ---
  const paginationConfig: PaginationProps = useMemo(() => {
    const { total = 0, current = 1, pageSize = 10 } = paginationRef.current;
    return {
      total,
      current,
      pageSize,
      showSizeChanger: true,
      showQuickJumper: true,
      showTotal: () => `共 ${total ?? 0} 条`,
      onChange: (page, size) => {
        setPagination(prev => ({
          ...prev,
          current: size !== prev.pageSize ? 1 : page,
          pageSize: size,
        }));
        getList();
      },
    };
  }, [JSON.stringify(paginationRef.current)]);

  // --- 清空所选行 ---
  const handleClearSelectedRowKeys = useCallback(() => {
    setSelectedRowKeys([]);
  }, [setSelectedRowKeys]);

  return {
    selectedRowKeys,
    setSelectedRowKeys,
    rowSelection,
    pagination: paginationRef.current,
    setPagination,
    paginationConfig,
    extraParams: extraParamsRef.current,
    setExtraParams,
    list,
    setList,
    getList,
    deleteItem,
    batchDelete,
    downloadExcel,
    downloadPending,
    calcPageAfterDelete,
    loading,
    setLoading,
    handleClearSelectedRowKeys,
  };
}
